package com.moss.street.market;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * The AdminServlet is the controller for all the admin screen actions.
 * 
 * @author drusk
 *
 */

public class AdminServlet extends HttpServlet implements Servlet
{
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {  
    	Connection conn = DerbyDatabase.getConnInstance();
    	
    	// set in AddStall.jsp
        String stallNumber = request.getParameter("stallnumber");
        String stallType = request.getParameter("stalltype");
        String stallLength = request.getParameter("stalllength");
        String stallWidth = request.getParameter("stallwidth");
        String stallFee = request.getParameter("stallfee");
        
    	// set in AddStall.jsp
        String modifyStallNumber = request.getParameter("modifystallnumber");
        String modifyStallType = request.getParameter("modifystalltype");
        String modifyStallLength = request.getParameter("modifystalllength");
        String modifyStallWidth = request.getParameter("modifystallwidth");
        String modifyStallFee = request.getParameter("modifystallfee");
        
        // set in AdminAddUser.jsp
        String newUsername = request.getParameter("newusername");
        String newPassword = request.getParameter("newpassword");
        String lastName = request.getParameter("lastname");
        String firstName = request.getParameter("firstname");
        String isStaffMemberYN = request.getParameter("newstaffmember");
        String emailAddress = request.getParameter("emailaddress");
        String contactInfo = request.getParameter("contactinfo");
        
        // set in AdminAddUser.jsp
        String modifyUserId = request.getParameter("modifyuserid");
        String modifyUsername = request.getParameter("modifyusername");
        String modifyPassword = request.getParameter("modifypassword");
        String modifyLastName = request.getParameter("modifylastname");
        String modifyFirstName = request.getParameter("modifyfirstname");
        String modifyIsStaffMemberYN = request.getParameter("modifystaffmember");
        String modifyEmailAddress = request.getParameter("modifyemailaddress");
        String modifyContactInfo = request.getParameter("modifycontactinfo");

        // set in AdminAddBooking.jsp
        String bookingForUserName = request.getParameter("bookingforusername");
        String bookingStallNumber = request.getParameter("bookingstallnumber");
        String dateReserved = request.getParameter("datereserved");
        String maintenance = request.getParameter("maintenance");
        String dateBookingMade = request.getParameter("datebookingmade");
        
        // set in AdminAddBooking.jsp
        String deleteBookingForUserName = request.getParameter("deletebookingforusername");
        String deleteBookingStallNumber = request.getParameter("deletebookingstallnumber");
        String deleteDateReserved = request.getParameter("deletedatereserved");
        String deleteMaintenance = request.getParameter("deletemaintenance");
        String deleteDateBookingMade = request.getParameter("deletedatebookingmade");
        
        // add stall
    	if (newUsername == null && bookingForUserName == null &&
    			stallNumber != null && stallType != null &&
    			stallLength != null && stallWidth != null &&
    			stallFee != null) {
    		// check for existing stall number
            StallsBean existingStall = DerbyDatabase.getStallDetails(conn, stallNumber);
            if (existingStall == null) {
            	DerbyDatabase.addStall(conn, stallNumber, stallType, stallLength,
            			stallWidth, stallFee);
            } else {
            	System.err.println("Stall number "+stallNumber+ " is already in database.");
            }
            getServletContext().getRequestDispatcher("/AddStall.jsp").forward(request, response);
            return;
        }
    	
    	// modify stall information
       	if (newUsername == null && bookingForUserName == null &&
       			stallNumber == null && modifyStallNumber != null &&
       			(modifyStallType != null || modifyStallLength != null ||
       			modifyStallWidth != null || modifyStallFee != null)) {

        		// check for existing stall number
                StallsBean existingStall = DerbyDatabase.getStallDetails(conn, modifyStallNumber);
                if (existingStall != null) {
                	DerbyDatabase.modifyStall(conn, modifyStallNumber, 
                			modifyStallType, modifyStallLength,
                			modifyStallWidth, modifyStallFee);
                } else {
                	System.err.println("Stall number "+stallNumber+ " is not in database.");
                }
                getServletContext().getRequestDispatcher("/AddStall.jsp").forward(request, response);
                return;
            }
       	
    	// add user
       	if (stallNumber == null && bookingForUserName == null &&
       			newUsername != null && newPassword != null &&
    			lastName != null && firstName != null &&
    			isStaffMemberYN != null && emailAddress != null &&
    			contactInfo != null) {
    		// check for existing username number
            UsersBean[] newUsers = DerbyDatabase.accountQuery(conn, newUsername);
            if (newUsers.length == 0) {
            	int result = DerbyDatabase.accountUpdate(conn, newUsername, newPassword,
            			lastName, firstName, isStaffMemberYN, emailAddress, contactInfo);
            	if (result != 1) {
            		System.err.println("Admin add user failed");
            	}
            } else {
            	System.err.println("Username " + newUsername + " is already in database.");
            }
            getServletContext().getRequestDispatcher("/AdminAddUser.jsp").forward(request, response);
            return;
        }
       	
    	// modify user information
       	if (stallNumber == null && bookingForUserName == null &&
       			newUsername == null && modifyUserId != null &&
       			modifyUsername != null && (modifyPassword != null ||
    			modifyLastName != null || modifyFirstName != null ||
    			modifyIsStaffMemberYN != null || modifyEmailAddress != null ||
    			modifyContactInfo != null)) {
    		// check for existing username number
            UsersBean[] modifyUsers = DerbyDatabase.accountQuery(conn, modifyUsername);
            if (modifyUsers.length == 1) {
            	int result = DerbyDatabase.accountUpdate(conn, modifyUserId, modifyUsername, modifyPassword,
            			modifyLastName, modifyFirstName, modifyIsStaffMemberYN, modifyEmailAddress, modifyContactInfo);
            	if (result != 1) {
            		System.err.println("Admin change user info failed");
            	}
            } else {
            	System.err.println("Username " + newUsername + " is not in database.");
            }
            getServletContext().getRequestDispatcher("/AdminAddUser.jsp").forward(request, response);
            return;
        }
       	
       	// add booking
        if (stallNumber == null && newUsername == null &&
        		bookingForUserName != null && bookingStallNumber != null &&
        		dateReserved != null && maintenance != null &&
        		dateBookingMade != null) {
        	// check for prior booking
        	BookingsBean priorBookings[] = DerbyDatabase.fetchBookings(conn, bookingStallNumber, dateReserved);
        	if (priorBookings.length == 0) {
        		int result = DerbyDatabase.bookingsUpdate(conn, bookingForUserName, bookingStallNumber,
        				dateReserved, maintenance, dateBookingMade);
            	if (result != 1) {
            		System.err.println("Admin add booking failed");
            	}
        	}else {
            	System.err.println("Stall number " + bookingStallNumber +
            			" has a prior reservation for " + dateReserved);
            }
            getServletContext().getRequestDispatcher("/AdminAddBooking.jsp").forward(request, response);
            return;
        	
        }
        
      	// delete booking
        if (stallNumber == null && newUsername == null &&
        		deleteBookingForUserName != null && deleteBookingStallNumber != null &&
        		deleteDateReserved != null && deleteMaintenance != null &&
        		deleteDateBookingMade != null) {
        	// check for booking
        	BookingsBean priorBookings[] = DerbyDatabase.fetchBookings(conn, deleteBookingStallNumber, deleteDateReserved);
        	if (priorBookings.length == 1) {
        		int result = DerbyDatabase.bookingsDelete(conn, deleteBookingForUserName, deleteBookingStallNumber,
        				deleteDateReserved, deleteMaintenance, deleteDateBookingMade);
            	if (result != 1) {
            		System.err.println("Admin delete booking failed");
            	}
        	}else {
            	System.err.println("Stall number " + deleteBookingStallNumber +
            			" has no prior reservation for " + deleteDateReserved);
            }
            getServletContext().getRequestDispatcher("/AdminAddBooking.jsp").forward(request, response);
            return;
        	
        }
        System.err.println("AdminServlet: Should never get here!  Parameter error.");
        getServletContext().getRequestDispatcher("/Admin.jsp").forward(request, response);
        return;
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    		throws ServletException, IOException {
            doPost(request,response);
    }
}
